package com.android.questions.config;

import android.content.Context;
import android.content.res.AssetManager;
import android.text.TextUtils;
import android.util.Log;

import com.android.base.util.DQLog;
import com.android.base.util.FileSizeUtil;
import com.android.questions.litepal.AnswerLitePalEntity;
import com.android.questions.util.Command;
import com.android.questions.util.DESManager;

import org.litepal.LitePal;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.util.List;

/**
 * FileName: AnswerDataConfig
 * Author: admin
 * Date: 2021/11/8 13:48
 * Description:
 */
public class AnswerDataConfig {

    public static String dirPath = null;

    public static void initAnswerData(Context context) {
        AnswerLitePalConfig.init();
        dirPath = context.getFilesDir() + "/a_txt/";
        File dirFile = new File(dirPath);
        if (!dirFile.exists()) {
            DQLog.e("路径不存在，创建路径：" + dirFile);
            dirFile.mkdirs();
        }

        new Thread(new Runnable() {
            @Override
            public void run() {
                List<AnswerLitePalEntity> litePalEntities = LitePal.findAll(AnswerLitePalEntity.class);
                for (AnswerLitePalEntity litePalEntity : litePalEntities) {
                    if (FileSizeUtil.getFileOrFilesSize(dirPath + litePalEntity.getFileName(), FileSizeUtil.SIZETYPE_KB) > 0) {
                        DQLog.e("本地已经有文件了:" + litePalEntity.getFileName());
                    } else {
                        String assetsData = getJson(litePalEntity.getAssetsName(), context);
//                        DQLog.i("读取到json原始数据：" + assetsData);
                        String encryptData = DESManager.encrypt(Command.DQ_ANSWER_TEST_DATA, assetsData);
//                        DQLog.i("加密过后的数据：" + encryptData);
                        writeFileContent(encryptData, dirPath, litePalEntity.getFileName());
                        DQLog.e("文件全路径地址：" + dirPath + litePalEntity.getFileName());
                    }
                }
            }
        }).start();
    }

    public static String getJson(String assetsName, Context context) {
        //将json数据变成字符串
        StringBuilder stringBuilder = new StringBuilder();
        try {
            //获取assets资源管理器
            AssetManager assetManager = context.getAssets();
            //通过管理器打开文件并读取
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    assetManager.open(assetsName)));
            String line;
            while ((line = bf.readLine()) != null) {
                stringBuilder.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return stringBuilder.toString().replaceAll(" ", "").trim();
    }

    /**
     * 读取txt文件
     *
     * @param filepath 本地txt或log文件
     * @return 返回读取到的文件内容
     */
    public static String readFileContent(Context context, String assetsPath, String filepath) {
        StringBuilder content = new StringBuilder();
        try {
            InputStream is = new FileInputStream(filepath);
            InputStreamReader reader = new InputStreamReader(is);
            BufferedReader bufferedReader = new BufferedReader(reader);
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                content.append(line).append("\n");
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NullPointerException e) {
            e.toString();
        }
        if (TextUtils.isEmpty(content.toString())) {
            content = new StringBuilder(getJson(assetsPath, context));
        }
        return content.toString();
    }

    /**
     * 字符串写入本地txt
     *
     * @param strcontent 文件内容
     * @param filePath   文件地址
     * @param fileName   文件名
     * @return 写入结果
     */
    private static boolean writeFileContent(String strcontent, String filePath, String fileName) {
        boolean isSavaFile = false;
        makeFilePath(filePath, fileName);
        String strFilePath = filePath + fileName;
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                DQLog.e("Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
            isSavaFile = true;
        } catch (Exception e) {
            isSavaFile = false;
            DQLog.e("Error on write File:" + e);
        }
        return isSavaFile;
    }

    /**
     * 生成文件
     *
     * @param filePath 文件地址
     * @param fileName 文件名
     */
    private static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    /**
     * 生成文件夹
     */
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e + "");
        }
    }
}
